#include <iostream>
#include <fstream>
#include <cmath>
#include <vector>

using namespace std;

void initLCA(const vector<int>& T, vector< vector<int> >& P, int n, int pSecondSize) {
    for (size_t i = 0; i < n; ++i) {
        P[i][0] = T[i];
    }

    for (size_t j = 1; j < pSecondSize; ++j) {
        for (size_t i = 0; i < n; ++i) {
            if (P[i][j - 1] != -1) { P[i][j] = P[P[i][j - 1]][j - 1]; }
        }
    }    
}

int getLCA(const vector<int>& T,const vector<vector<int> >& P,const vector<int>& L, int p, int q) {
    int tmp;

    if (L[p] < L[q]) {
        tmp = p;
        p = q;
        q = tmp;
    }

    int lg = (int)floor(log((double)L[p]) / log(2.0));

    for (int i = lg; i >= 0; --i) {
        if (L[p] - (1 << i) >= L[q]) {
            p = P[p][i];
        }
    }

    if (p == q) {
        return p;
    }

    for (int i = lg; i >= 0; --i) {
          if (P[p][i] != -1 && P[p][i] != P[q][i]) {
              p = P[p][i];
              q = P[q][i];
          }
    }

    return T[p];
}


int main() {
    if(freopen("in.txt", "r", stdin)==NULL) {
        cout<<"Error: input file can't be opened";
        return 1;
    }

    int n = 0;
    cin>>n;
    ++n;

    vector<int> T(n);
    vector<int> L(n, 0);
    int pSecondSize = (int)floor(log((double)n) / log(2.0));

    vector<int> tmp(pSecondSize, -1);
    vector<vector<int> > P(n, tmp);

    int p, q;
    for (size_t i = 0; i < n - 1; ++i) {
        cin>>p>>q;
        T[p] = q;
        L[p] = L[q] + 1;
    }
    T[0] = -1;

    initLCA(T, P, n, pSecondSize);

    int m;
    cin>>m;

    for (int i = 0; i < m; ++i) {
        cin>>p>>q;
        cout<<getLCA(T, P, L, p, q)<<endl;
    }

    system("pause");
    return 0;
}